package com.zkthink.ceres.member.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import com.zkthink.base.R;
import com.zkthink.base.controller.SuperController;
import com.zkthink.ceres.member.dto.MemberTagPageDTO;
import com.zkthink.ceres.member.dto.MemberTagSaveDTO;
import com.zkthink.ceres.member.dto.MemberTagUpdateDTO;
import com.zkthink.ceres.member.entity.MemberTag;
import com.zkthink.ceres.member.service.MemberTagRelService;
import com.zkthink.ceres.member.service.MemberTagService;
import com.zkthink.ceres.member.vo.MemberTagCountVO;
import com.zkthink.ceres.member.vo.MemberTagVO;
import com.zkthink.security.annotation.PreAuth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * <p>
 * 前端控制器 会员标签
 *
 * </p>
 *
 * @author kellen
 * @date 2020-07-12
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/memberTag")
@Api(value = "MemberTag", tags = "会员标签")
@PreAuth(replace = "memberTag:")
@AllArgsConstructor
public class MemberTagController extends
    SuperController<MemberTagService, Long, MemberTag, MemberTagPageDTO, MemberTagSaveDTO, MemberTagUpdateDTO> {

  private MemberTagRelService tagRelService;


  @Override
  public void handlerResult(IPage<MemberTag> page) {
    List<MemberTag> memberTagList = page.getRecords();
    if (!CollectionUtils.isEmpty(memberTagList)) {
      List<Long> tagIds = memberTagList.stream().map(MemberTag::getId).collect(Collectors.toList());
      List<MemberTagCountVO> countVOList = tagRelService.queryMemberTagCountList(tagIds);
      if (!CollectionUtils.isEmpty(countVOList)) {
        Map<Long, MemberTagCountVO> memberTagCountVOMap = Maps.newHashMap();
        countVOList.forEach(e -> memberTagCountVOMap.put(e.getTagId(), e));
        memberTagList.forEach(e -> {
          MemberTagCountVO countVO = memberTagCountVOMap.get(e.getId());
          if (null != countVO) {
            e.setTagCount(countVO.getCount());
          }
        });
      }
    }
  }

  /**
   * 查询客户已打标签
   */
  @ApiOperation(value = "查询客户已打标签")
  @GetMapping(value = "/queryTag/{mid}")
  public R<List<MemberTagVO>> queryTag(@PathVariable("mid") Long mid) {
    List<MemberTagVO> tagVOList = tagRelService.findByMid(mid);
    return R.success(tagVOList);
  }


}
